import React, { useState, useEffect } from 'react';
import { Button, Divider, Tree } from 'antd';
import { useHistory } from 'react-router-dom';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, 
  buildtree
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import { SaveOutlined } from '@ant-design/icons';
import { use_wlfl_old_initformdata } from './use_baseinfo_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;



const Wlda_form_wlfl = (ifshowfl) => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    kfkhdaOptions: [],
    wlda_cp: [], wlda_mj: [], gd_mjmx: []
  })

  //主表数据
  const [formdata, setformdata] = useState(use_wlfl_old_initformdata())

  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/baseinfo/query_wlfl_byid", 'POST', { id }, "json")
    console.log(rtdata.resultdata.formdata)
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
    await querywlfllist();


  }

  const querywlfllist = async () => {
    let wlflrtdata = await fetchsync_util("/admin/baseinfo/wlfllb", 'POST', {}, "json")
    let listdata=wlflrtdata.resultdata;
    var treedata=buildtree(listdata,'000');
    let newformdata={...formdata}
    newformdata.sjflmc.selectdata=treedata;
    setformdata({...newformdata})
  }


  // 页面进入加载数据
  useEffect(() => {
    JSON.parse(storage.pre_wlda_item).type == "edit" ? loadformdata(JSON.parse(storage.pre_wlda_item).data.id) : ""
    querywlfllist()
  }, [])


  //设置value
  const setfield = (onekey, value, settype,extra) => {
    extra?console.log(extra):""
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });

      if(onekey=='sjflmc'){
        newformdata.sjflid.value=extra.key
        newformdata.sjflbm.value=extra.value

      }
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }


  const handleupload = async () => {


    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。
    
    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage);return; }
    else;
    //设置submit url
    var uploadurl = JSON.parse(storage.pre_wlda_item).type == "add" ?
      "/admin/baseinfo/add_wlfl" : "/admin/baseinfo/update_wlfl";

      //flbm=sjflbm+flbm
      formdata.flbm.value=formdata.sjflbm.value+''+formdata.flbm.value
    let rtdata = await fetchsync_util(uploadurl, 'POST', { formdata }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
  await  querywlfllist()

    // history.push({ pathname: '/shipSRM/baseinfo/wldalb' })
  }



  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype,extra) => { setfield(key, value, settype,extra) }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype,extra) => { setfield(key, value, settype,extra) }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={styles.maincontainer}>

      <div style={styles.kshcontainerleft}>
        <div style={{ textIndent: "0.4rem", color: "#2c4799", fontWeight: "800", fontSize: "0.7rem" }}>物料分类</div>
        <Tree
          treeLine={true}
          style={{
            width: "80%",
          }}
          listHeight={400}
          showSearch
          treeData={formdata.sjflmc.selectdata}
          showLine={true}
          defaultExpandedKeys={["C", "B", "Y"]}

        />
      </div>

      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "96%", marginLeft: "2%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
        <br />

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem" }}>
          <SaveOutlined />{JSON.parse(storage.pre_wlda_item).type == "add" ? "新增" : "修改"}</Button>

          <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem",
            marginLeft:"0.5rem"
          }}>
          <SaveOutlined />修改</Button>

          
          <Button type="primary" onClick={handleupload}
          style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.6rem",
            marginLeft:"0.5rem"
          }}>
          <SaveOutlined />删除</Button>
        {/* 主表区域结束 */}
        <Divider></Divider>

      </div>


    </div>
  )
}


export default Wlda_form_wlfl

var styles = {
  maincontainer: {
    height: "80vh", backgroundColor: `white`, top: "0",
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
    topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
butdcstyle: { paddingLeft:"1vw",paddingRight:"1vw",height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butmainstyle: {paddingLeft:"1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%",fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw"},
  kshcontainer: {
    width: "79%", height: "90%", position: "absolute", top: "0.5vw", right: "0vw", backgroundColor: "white", color: "black",
    borderRadius: "10px",
  },
  kshcontainerleft: {
    width: "20%", height: "90%", position: "absolute", top: "0.5vw", left: "0vw", backgroundColor: "#f7f8fa", color: "black",
    borderRadius: "10px",
  },
}
